import requests
import json
import consul
import random
class ProxyClass:
    def getServiceIp(self, env_dict):
        con = consul.Consul(env_dict["consul_host"], env_dict["consul_port"])
        data = con.health.service(env_dict["data_dc"], dc=env_dict["fiona_dc"])
        if len(data) < 2:
            return None
        serviceList = data[1]
        ipList = []
        for item in serviceList:
            ip = self.getNodeIp(item)
            if ip is not None:
                ipList.append(ip)
        if len(ipList) == 0:
            return None
        index = random.randint(0, len(ipList) - 1)
        return ipList[index]
    
    def getNodeIp(self, data):
        checks = data.get("Checks")
        isPassing = True
        for check in checks:
            if check.get("Status") == 'passing':
                continue
            isPassing = False
            break
        if not isPassing:
            return None
        ip = data.get("Service").get("Address")
        if ip is None or len(ip) == 0:
            ip = data.get("Node").get("Address")
        port = data.get("Service").get("Port")
        return ip + ":" + str(port)
    
    def get_proxyman_ip(self, env_dict):
        return self.getServiceIp(env_dict)
    
    def get_proxies(self, env="dev", proxies_type='http', timeout=20):
        dev_dict = {
            "consul_host": "dc1.u51-inc.com",
            "consul_port": 8500,
            "fiona_dc": "stable",
            "fiona_profile": "dev",
            "data_dc": "proxyman",
            "Authorization": "service 4ZHZDMGjMD5RFKyAeDiXZpPtIXS8y7TXPPvWCmN9YNs9CxZfbRQ0ruj8sH2LKM",
        }
        prod_dict = {
            "consul_host": "127.0.0.1",
            "consul_port": 8500,
            "fiona_dc": "xydc",
            "fiona_profile": "product",
            "data_dc": "proxyman",
            "Authorization": "service 4ZHZDMGjMD5RFKyAeDiXZpPtIXS8y7TXPPvWCmN9YNs9CxZfbRQ0ruj8sH2LKM",
        }
        if env == "dev":
            env_dict = dev_dict
        else:
            env_dict = prod_dict
        
        proxyman_ip = self.get_proxyman_ip(env_dict)
        
        level = 9
        holdSeconds = timeout
        url = f"http://{proxyman_ip}/proxyman/api/v5/proxies?level={level}&holdSeconds={holdSeconds}"
        # 正式服/172.19.135.22:8080
        headers = {
            "Content-Type": "application/json",
            "Authorization": "service 4ZHZDMGjMD5RFKyAeDiXZpPtIXS8y7TXPPvWCmN9YNs9CxZfbRQ0ruj8sH2LKM",
            "X-Consumer-ID": "u51.com",
        }
        try:
            result = requests.get(url, headers=headers, verify=False, timeout=6).json()
            ipaddr = result["ipaddr"]
            port = result["port"]
            proxies = {
                # "http": f"http://{ipaddr}:{port}",
                "https": f"https://{ipaddr}:{port}"
            }
        except Exception as e:
            print("获取代理出现异常")
            proxies = {}
        return proxies

pc =ProxyClass()

def get_anti_content():
    # url = "http://0.0.0.0:8889/get_anti_content"
    url = "http://119.45.102.125:8889/get_anti_content"

    res = requests.get(url)
    return json.loads(res.text).get("anti_content")

def get_sku_api(accesstoken,goodsId):
    # anti_content = "0aoAfoyZrOloU99wvg8LOx3XIQgwnOlj8FKZ9SVQ2On9t-IecCXXnfj2VZdH59HRTqNdJjQblE-biDmoJntbA4nncDz-hzv3be3XNrSa3V4DQw8MspMLUaIHWLO_xgOvNMn08wg5WIg0aMjTSTIORcpqiQjBETXdwpZUB0HEYEhPTJ00RITaJpZVRy00s01_TPb-mCf03k4Kfw2t5YKdoiFgtkrvl7xkGcnNgbFB7AwJJs1asnvzGjA7JnlEzdBhCuoQo9aCsJ4dEGQoeYa-wqG_dNeso7g4p4SNOI016r2XIzTS47pVpJ65WFtbNfFaQBmg0QWPw9Xif_hynNI7JynrxFBSFHHwjvHV5K5ZwY60uvITz1_ifsOcasLAv7hRieqDsC8Xjfen2fLG8QA6YeYNHxDp62GaBGqmD115Yk0mDO9lqKv9rGGAULceI7ksNjJurd"
    anti_content = get_anti_content()
    print(anti_content)

    headers = {
        "authority": "api.pinduoduo.com",
        "pragma": "no-cache",
        "cache-control": "no-cache",
        "sec-ch-ua": "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"97\", \"Chromium\";v=\"97\"",
        # "accesstoken": "2RB326FJKZUCROLEVWG4GROVYT5VLEOI5ULCKYBVTJARXMN4C2PA1126f82",
        # "accesstoken": "H2AOSFRQND55TJXMCMZQVBPKEF7ALADUCCX2WNA4TICMKTM3E3GA1126f82",
        "accesstoken": accesstoken,
        "content-type": "application/json; charset=UTF-8",
        "sec-ch-ua-mobile": "?0",
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
        "sec-ch-ua-platform": "\"macOS\"",
        "accept": "*/*",
        "origin": "https://youhui.pinduoduo.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://youhui.pinduoduo.com/",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8"
    }
    # cookies = {
    #     "api_uid": "rBUUSWHn5z8fiS7ayBm7Ag=="
    #       # api_uid=rBUUiGHuceVowjMWPSfDAg==
    # }
    # p = pc.get_proxies()
    # print(p)
    url = "https://api.pinduoduo.com/api/jinbao/h5_weak_auth/goods/query_goods_detail_and_sku"
    data = {
        "goodsId": goodsId,
        "goodsIds": [
            goodsId
        ],
        "pid": None,
        "antiContent": anti_content,
        "anti_content": anti_content
    }
    data = json.dumps(data)
    response = requests.post(url, headers=headers,data=data)  #cookies=cookies,,proxies=p

    print(response.text)
    print(response)


if __name__ == '__main__':
    get_sku_api("6UN6HH6LRC2T6OHCXWBAXNQFTQUGJZYCZM2NP26Q7SDN2VHGBDAA110896e", "82724960456")

